package client

import (
	"context"
	"google.golang.org/grpc"
	"zk507/common/proto/user"
)

type Handler func(ctx context.Context, in user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8008", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := user.NewUserClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	defer dial.Close()
	return res, nil
}

func UserLogin(ctx context.Context, i *user.UserLoginRequest) (*user.UserLoginResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		res, err := in.UserLogin(ctx, i)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserLoginResponse), nil
}
func Sms(ctx context.Context, i *user.SmsRequest) (*user.SmsResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		res, err := in.Sms(ctx, i)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.SmsResponse), nil
}

func InformationSynchronous(ctx context.Context, i *user.InformationSynchronousRequest) (*user.InformationSynchronousResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		res, err := in.InformationSynchronous(ctx, i)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.InformationSynchronousResponse), nil
}
func InformationList(ctx context.Context, i *user.InformationListRequest) (*user.InformationListResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		res, err := in.InformationList(ctx, i)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.InformationListResponse), nil
}
